<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box">
    <CommonDateSearch ref="searchRef" @search="handleSearch"></CommonDateSearch>
    <div class="content-box">
      <Card class="card-flex chart">
        <Bar ref="barRef" class="bar"></Bar>
      </Card>
      <Card class="common-card flex table-box">
        <BasicTable @register="registerTable" :showIndexColumn="false"></BasicTable>
      </Card>
    </div>
  </PageWrapper>
</template>
<script setup>
import Line from '@/components/Charts/Line/index.vue'
import { Card } from 'ant-design-vue'
import { ref, onMounted, reactive } from 'vue'
import { PageWrapper } from '@/components/Page'
import CommonDateSearch from '@/components/CommonDateSearch/index.vue'
import Icon from '@/components/Icon/Icon.vue'
import { getChartChildListData } from '@/api/common/chart'
import { BasicTable, useTable } from '@/components/Table'
import { getCompareBarChartEle } from '@/api/power/electricity/electricity.ts'
import Bar from './Bar.vue'

defineOptions({ name: 'PeakValley' })

const searchRef = ref()
const searchInfo = reactive({})
let barRef = ref()
const loadingRef = ref(false)
const chartData = ref()
const [registerTable, { setLoading, setColumns, setTableData }] = useTable({
  rowKey: 'id',
  columns: [],
  pagination: false,
  formConfig: {
    labelWidth: 120,
  },
  bordered: true,
  striped: false,
})

onMounted(() => {
  searchRef.value.handleSearch()
})

const handleSearch = (params) => {
  Object.assign(searchInfo, params)
  barRef.value.getData(searchInfo)
  getData()
}

const formatHeader = (headerData) => {
  const headerList = headerData.map((item) => ({
    title: item,
    dataIndex: item,
    width: 100,
    customRender: ({ text }) => {
      return text || '--'
    },
  }))
  headerList.unshift({
    title: '描述',
    dataIndex: 'name',
    width: 120,
    fixed: 'left',
    merge: true,
  })

  setColumns(headerList)
}

const formatTableData = (tableData) => {
  const { xaxisList, yaxisList } = tableData
  const data = yaxisList.map((item) => {
    const { data, ...others } = item
    const record = { ...others }
    data.forEach((item, index) => {
      record[xaxisList[index]] = item
    })
    return record
  })
  setTableData(data)
}

const getData = () => {
  loadingRef.value = true
  getCompareBarChartEle({
    ...searchInfo,
  })
    .then((res) => {
      chartData.value = res
      formatTableData(res)
      formatHeader(res.xaxisList)
    })
    .finally(() => {
      loadingRef.value = false
    })
}
</script>
<style scoped lang="scss">
.content-box {
  display: flex;
  flex: 1;
  flex-direction: column;
  overflow: auto;

  .chart {
    min-height: 340px;
  }

  .table-max-height {
    flex-grow: 1;
    max-height: 100%;
  }

  .ant-card {
    flex-shrink: 0;
    overflow: hidden;

    &:not(:last-child) {
      margin-bottom: 20px;
    }
  }
}
</style>
